package org.inspiration.dudu.user.service.impl;


import lombok.RequiredArgsConstructor;
import org.inspiration.dudu.common.constant.RedisConstant;
import org.inspiration.dudu.common.util.RedisUtil;
import org.inspiration.dudu.user.mapper.UserMapper;
import org.inspiration.dudu.user.model.entity.UserLikeEntity;
import org.inspiration.dudu.user.service.UserLikeConsumerService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserLikeConsumerServiceImpl implements UserLikeConsumerService {

    private final UserMapper userMapper;
    private final RedisUtil redisUtil;

    @Override
    @RabbitListener(queues = "${dudu.rabbitmq.exchanges.like-exchange.queues.user-like-queue.name}")
    public void handleChangeUserLikeCount(Map<String, Object> map) {
        try {
            UserLikeEntity userLikeEntity = (UserLikeEntity) map.get("userLikeEntity");
            Long userId = userLikeEntity.getTargetUserId();
            String action = (String) map.get("action");
            if ("like".equals(action)) {
                // 添加所获点赞量
                userMapper.increaseLikeCount(userId);
                // 添加未读消息数量，如果存在缓存先写缓存再写数据库
                redisUtil.incrementHashFieldWithLua(RedisConstant.USER_KEY_PREFIX + userId, "unreadLikeCount");
                userMapper.increaseUnreadLikeCount(userId);
            } else if ("unlike".equals(action)) {
                userMapper.decreaseLikeCount(userId);
                // 先判断点赞消息是否已读，如果已读那么不用减少未读消息的数量，如果未读则需要减少
                Boolean isRead = userLikeEntity.getIsRead();
                if (!isRead) {
                    redisUtil.decrementHashFieldWithLua(RedisConstant.USER_KEY_PREFIX + userId, "unreadLikeCount");
                    userMapper.decreaseUnreadLikeCount(userId);
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

}
